//controllers/index.js

const async = require('async');
const wishModel = require('../models/wish');
const constant = require('../constant/constant');

const exportObj = {
    getList,
    add
};

module.exports = exportObj;

// 获取许愿列表
function getList(req, res){
    //定义一个async任务
    let tasks = {
        //执行查询方法
        query: cb => {
            wishModel.findAll({
                limit: 50,
                order: [['created_at', 'DESC']]
            }).then(result => {
                let list = [];
                result.forEach(val => {
                    let date = new Date(val.createdAt);
                    date = date.getFullYear() + '.' + date.getMonth() + '.' + date.getDate();
                    let obj = {
                        id: val.id,
                        name: val.name,
                        content: val.content,
                        createdAt: date
                    };
                    list.push(obj);
                });
                cb(null, list);
            }).catch(err => {
                console.log(err);
                cb(constant.DEFAULT_ERROR);
            })
        }
    };
    async.auto(tasks, (err, result) => {
        if(err){
            console.log(err);
        }else {
            res.render('index', {
                list: result['query']
            })
        }
    })
}

// 添加许愿方法
function add(req, res){
    let tasks = {
        add: cb => {
            wishModel.create({
                name: req.body.name,
                content: req.body.content,
            }).then(result => {
                cb(constant.DEFAULT_SUCCESS);
            }).catch(err => {
                console.log(err);
                cb(constant.DEFAULT_ERROR);
            })
        }
    };
    async.auto(tasks, (err, result) => {
        if(err){
            console.log(err);
            res.send(err);
        }else {
            res.send(result);
        }
    })
}